//Three States:https://www.luogu.com.cn/problem/CF590C

#include <iostream>
#include <cstring>
#include <deque>

using namespace std;

const int N = 1010;
char p[N][N];
int n,m;
int f[4][N][N];

int dx[] = {0,0,1,-1};
int dy[] = {-1,1,0,0};
void bfs(int num)
{
	memset(f[num],-1,sizeof f[num]);
	deque<pair<int,int>> q;
	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < m; j++)
		{
			if(p[i][j] == num + '0')
			{
				f[num][i][j] = 0;
				q.push_back({i,j});
			}
		}
	}
	
	while(q.size())
	{
		pair<int,int> t = q.front();
		q.pop_front();
		int x = t.first;
		int y = t.second;
		for(int i = 0; i < 4; i++)
		{
			int a = x + dx[i];
			int b = y + dy[i];
			if(a < 0 || b < 0 || a >= n || b >= m)continue;
			if(p[a][b] == '#')continue;
			int w = (p[a][b] == '.' ? 1 : 0);
			if(f[num][a][b] == -1)
			{
				f[num][a][b] = f[num][x][y] + w;
				if(w == 0)
				{
					q.push_front({a,b});
				}
				else
				{
					q.push_back({a,b});
				}
			}
			else if(f[num][a][b] > f[num][x][y]+w)
			{
				f[num][a][b] = f[num][x][y] + w;
			}
		}
	}
	
}

int main()
{
	cin >> n >> m;
	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < m; j++)
		{
			cin >> p[i][j];
		}
	}
	
	bfs(1);
	bfs(2);
	bfs(3);

	

	int ret = -1;
	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < m; j++)
		{
			int x =f[1][i][j],y=f[2][i][j],z=f[3][i][j];
			if(p[i][j] != '#'&& x != -1 && y!=-1 && z != -1)
			{
				if(p[i][j] == '.')
				{
					if(ret == -1)
						ret = x + y + z - 2;
					else
						ret = min(ret,x + y + z - 2);
				}
				else 
				{
					if(ret == -1)
						ret = x + y + z;
					else
						ret = min(ret,x + y + z);

				}
			}
		}	
	}
	cout << ret;
	return 0;
}


